//! 数据网关CLI主程序

use std::sync::Arc;
use clap::{Parser, Subcommand};
use tokio::time::{sleep, Duration};
use tracing::{info, error};

use data_gateway_kernel::DataGatewayKernel;
use data_gateway_flight_sql::{FlightSqlServer, server::FlightSqlServerConfig};
use data_gateway_gateway::{HttpServer, HttpServerConfig};

#[derive(Parser)]
#[command(name = "data-gateway")]
#[command(about = "数据网关系统命令行工具")]
#[command(version = env!("CARGO_PKG_VERSION"))]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// 启动服务器
    Start {
        /// 配置文件路径
        #[arg(short, long)]
        config: Option<String>,
        /// HTTP端口
        #[arg(long, default_value = "8080")]
        http_port: u16,
        /// Flight SQL端口
        #[arg(long, default_value = "50051")]
        flight_port: u16,
        /// 启用详细日志
        #[arg(short, long)]
        verbose: bool,
    },
    /// 停止服务器
    Stop,
    /// 查看状态
    Status {
        /// 服务器地址
        #[arg(long, default_value = "http://localhost:8080")]
        server: String,
    },
    /// 执行查询
    Query {
        /// 查询内容
        #[arg(short, long)]
        sql: String,
        /// 服务器地址
        #[arg(long, default_value = "http://localhost:8080")]
        server: String,
    },
    /// 运行脚本
    Run {
        /// 脚本文件路径
        script: String,
    },
    /// 运行基准测试
    Benchmark {
        /// 测试类型
        #[arg(short, long, default_value = "all")]
        test_type: String,
        /// 迭代次数
        #[arg(short, long, default_value = "1000")]
        iterations: usize,
    },
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();

    // 初始化日志
    let log_level = match &cli.command {
        Commands::Start { verbose, .. } if *verbose => tracing::Level::DEBUG,
        _ => tracing::Level::INFO,
    };

    tracing_subscriber::fmt()
        .with_max_level(log_level)
        .init();

    match cli.command {
        Commands::Start { config, http_port, flight_port, verbose: _ } => {
            start_server(config, http_port, flight_port).await?;
        }
        Commands::Stop => {
            stop_server().await?;
        }
        Commands::Status { server } => {
            check_status(&server).await?;
        }
        Commands::Query { sql, server } => {
            execute_query(&sql, &server).await?;
        }
        Commands::Run { script } => {
            run_script(&script).await?;
        }
        Commands::Benchmark { test_type, iterations } => {
            run_benchmark(&test_type, iterations).await?;
        }
    }

    Ok(())
}

/// 启动服务器
async fn start_server(config: Option<String>, http_port: u16, flight_port: u16) -> anyhow::Result<()> {
    info!("🚀 启动数据网关系统");

    if let Some(config_path) = config {
        info!("📄 使用配置文件: {}", config_path);
    }

    // 创建内核
    info!("📦 初始化微内核系统...");
    let kernel = Arc::new(DataGatewayKernel::new().await?);
    info!("✅ 微内核系统初始化完成");

    // 启动Flight SQL服务器
    info!("🛩️ 启动Flight SQL服务器 (端口: {})...", flight_port);
    let flight_config = FlightSqlServerConfig {
        bind_address: format!("0.0.0.0:{}", flight_port).parse()?,
        enable_tls: false,
        tls_cert_path: None,
        tls_key_path: None,
        max_concurrent_connections: 1000,
        request_timeout_seconds: 30,
    };

    let flight_server = FlightSqlServer::new(flight_config, kernel.clone());
    let flight_handle = tokio::spawn(async move {
        if let Err(e) = flight_server.start().await {
            error!("❌ Flight SQL服务器启动失败: {}", e);
        }
    });

    // 启动HTTP服务器
    info!("🌐 启动HTTP API网关 (端口: {})...", http_port);
    let http_config = HttpServerConfig {
        host: "0.0.0.0".to_string(),
        port: http_port,
        enable_cors: true,
        request_timeout_seconds: 30,
    };

    let http_server = HttpServer::new(http_config, kernel.clone());
    let http_handle = tokio::spawn(async move {
        if let Err(e) = http_server.start().await {
            error!("❌ HTTP服务器启动失败: {}", e);
        }
    });

    // 等待服务器启动
    sleep(Duration::from_millis(500)).await;

    info!("🎉 数据网关系统启动完成!");
    info!("📡 Flight SQL服务器: 0.0.0.0:{}", flight_port);
    info!("🌐 HTTP API网关: http://0.0.0.0:{}", http_port);
    info!("💡 使用 Ctrl+C 停止服务器");

    // 等待中断信号
    tokio::select! {
        _ = tokio::signal::ctrl_c() => {
            info!("📡 收到停止信号，正在关闭服务器...");
        }
        _ = flight_handle => {
            error!("❌ Flight SQL服务器意外退出");
        }
        _ = http_handle => {
            error!("❌ HTTP服务器意外退出");
        }
    }

    info!("✅ 数据网关系统已停止");
    Ok(())
}

/// 停止服务器
async fn stop_server() -> anyhow::Result<()> {
    info!("🛑 停止数据网关服务器...");
    // TODO: 实现优雅停止逻辑
    info!("✅ 服务器已停止");
    Ok(())
}

/// 检查服务器状态
async fn check_status(server: &str) -> anyhow::Result<()> {
    info!("📊 检查服务器状态: {}", server);

    let client = reqwest::Client::new();
    let url = format!("{}/status", server);

    match client.get(&url).send().await {
        Ok(response) => {
            if response.status().is_success() {
                let text = response.text().await?;
                info!("✅ 服务器运行正常");
                println!("{}", text);
            } else {
                error!("❌ 服务器返回错误状态: {}", response.status());
            }
        }
        Err(e) => {
            error!("❌ 无法连接到服务器: {}", e);
        }
    }

    Ok(())
}

/// 执行查询
async fn execute_query(sql: &str, server: &str) -> anyhow::Result<()> {
    info!("🔍 执行查询: {}", sql);

    let client = reqwest::Client::new();
    let url = format!("{}/query", server);

    let request_body = serde_json::json!({
        "query_type": "sql",
        "query": sql,
        "params": {}
    });

    match client.post(&url)
        .json(&request_body)
        .send()
        .await
    {
        Ok(response) => {
            if response.status().is_success() {
                let text = response.text().await?;
                info!("✅ 查询执行成功");
                println!("{}", text);
            } else {
                error!("❌ 查询执行失败: {}", response.status());
            }
        }
        Err(e) => {
            error!("❌ 查询请求失败: {}", e);
        }
    }

    Ok(())
}

/// 运行脚本
async fn run_script(script_path: &str) -> anyhow::Result<()> {
    info!("📜 运行脚本: {}", script_path);

    // 读取脚本文件
    let script_content = tokio::fs::read_to_string(script_path).await?;

    // 创建解析器和执行器
    let mut parser = data_gateway_parser::ScriptParser::new();
    let context = data_gateway_parser::ScriptContext::new();
    let mut executor = data_gateway_parser::ScriptExecutor::new(context);

    // 解析脚本
    let program = parser.parse(&script_content)?;

    // 执行脚本
    let result = executor.execute(program).await?;

    info!("✅ 脚本执行完成");
    println!("执行时间: {:.2}ms", result.stats.execution_time_ms);

    Ok(())
}

/// 运行基准测试
async fn run_benchmark(test_type: &str, iterations: usize) -> anyhow::Result<()> {
    info!("🏃 运行基准测试: {} (迭代次数: {})", test_type, iterations);

    // 创建解析器和执行器进行测试
    let mut parser = data_gateway_parser::ScriptParser::new();
    let context = data_gateway_parser::ScriptContext::new();

    let start_time = std::time::Instant::now();

    for i in 0..iterations {
        // 解析脚本
        let program = parser.parse("var result = 1 + 2 * 3;")?;

        // 执行脚本
        let mut executor = data_gateway_parser::ScriptExecutor::new(context.clone());
        let _ = executor.execute(program).await?;

        if i % 100 == 0 && i > 0 {
            info!("📊 已完成 {} 次迭代", i);
        }
    }

    let elapsed = start_time.elapsed();
    let avg_time = elapsed.as_millis() as f64 / iterations as f64;
    let throughput = iterations as f64 / elapsed.as_secs_f64();

    info!("✅ 基准测试完成");
    println!("📊 测试结果:");
    println!("  - 总时间: {:.2}秒", elapsed.as_secs_f64());
    println!("  - 平均延迟: {:.2}ms", avg_time);
    println!("  - 吞吐量: {:.2} ops/sec", throughput);

    Ok(())
}
